package com.simplehire.controller;

import com.simplehire.entity.JobDescription;
import com.simplehire.entity.ResumeMatchResult;
import com.simplehire.model.User;
import com.simplehire.service.JobMatchingService;
import com.simplehire.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 岗位匹配控制器 - MVP V3
 * 核心功能：岗位JD匹配和评分
 */
@Controller
@RequestMapping("/job-matching")
public class JobMatchingController {
    
    private static final Logger logger = LoggerFactory.getLogger(JobMatchingController.class);
    
    @Autowired
    private JobMatchingService jobMatchingService;
    
    /**
     * 显示岗位匹配主页
     */
    @GetMapping
    public String showJobMatchingPage(Model model, Authentication authentication) {
        User currentUser = (User) authentication.getPrincipal();
        
        // 获取所有激活的岗位
        List<JobDescription> jobs = jobMatchingService.getAllActiveJobs();
        model.addAttribute("jobs", jobs);
        
        // 获取用户匹配历史
        List<ResumeMatchResult> matchHistory = jobMatchingService.getUserMatchHistory(currentUser);
        model.addAttribute("matchHistory", matchHistory);
        
        // 获取用户统计信息
        JobMatchingService.UserMatchStats stats = jobMatchingService.getUserStats(currentUser);
        model.addAttribute("stats", stats);
        
        // 添加选项数据
        addFormOptions(model);
        
        return "job-matching";
    }
    
    /**
     * 显示岗位详情页
     */
    @GetMapping("/job/{jobId}")
    public String showJobDetails(@PathVariable Long jobId, Model model, Authentication authentication) {
        try {
            JobDescription job = jobMatchingService.getJobById(jobId);
            model.addAttribute("job", job);
            
            User currentUser = (User) authentication.getPrincipal();
            
            // 检查是否已有匹配结果
            List<ResumeMatchResult> userHistory = jobMatchingService.getUserMatchHistory(currentUser);
            ResumeMatchResult existingMatch = userHistory.stream()
                .filter(result -> result.getJobDescription().getId().equals(jobId))
                .findFirst()
                .orElse(null);
            
            model.addAttribute("existingMatch", existingMatch);
            
            return "job-details";
            
        } catch (Exception e) {
            logger.error("获取岗位详情失败: {}", e.getMessage());
            model.addAttribute("error", "岗位不存在或已被删除");
            return "redirect:/job-matching";
        }
    }
    
    /**
     * 处理简历与岗位匹配
     */
    @PostMapping("/match")
    public String matchResumeWithJob(@RequestParam("jobId") Long jobId,
                                   @RequestParam("resumeText") String resumeText,
                                   Authentication authentication,
                                   RedirectAttributes redirectAttributes) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        try {
            // 验证输入
            if (resumeText == null || resumeText.trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "请输入简历内容");
                return "redirect:/job-matching/job/" + jobId;
            }
            
            if (resumeText.trim().length() < 50) {
                redirectAttributes.addFlashAttribute("error", "简历内容太短，请提供更详细的信息");
                return "redirect:/job-matching/job/" + jobId;
            }
            
            if (resumeText.length() > 10000) {
                redirectAttributes.addFlashAttribute("error", "简历内容过长，请控制在10000字符以内");
                return "redirect:/job-matching/job/" + jobId;
            }
            
            // 执行匹配分析
            ResumeMatchResult matchResult = jobMatchingService.matchResumeWithJob(currentUser, jobId, resumeText.trim());
            
            redirectAttributes.addFlashAttribute("success", "匹配分析完成！");
            return "redirect:/job-matching/result/" + matchResult.getId();
            
        } catch (Exception e) {
            logger.error("简历匹配分析失败: {}", e.getMessage());
            redirectAttributes.addFlashAttribute("error", "匹配分析失败：" + e.getMessage());
            return "redirect:/job-matching/job/" + jobId;
        }
    }
    
    /**
     * 显示匹配结果页
     */
    @GetMapping("/result/{resultId}")
    public String showMatchResult(@PathVariable Long resultId, Model model, Authentication authentication) {
        try {
            User currentUser = (User) authentication.getPrincipal();
            
            // 获取匹配结果
            List<ResumeMatchResult> userHistory = jobMatchingService.getUserMatchHistory(currentUser);
            ResumeMatchResult matchResult = userHistory.stream()
                .filter(result -> result.getId().equals(resultId))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("匹配结果不存在或无权访问"));
            
            model.addAttribute("matchResult", matchResult);
            model.addAttribute("job", matchResult.getJobDescription());
            
            // 计算匹配等级的颜色和样式
            String levelColor = getMatchLevelColor(matchResult.getMatchLevel());
            model.addAttribute("levelColor", levelColor);
            
            return "match-result";
            
        } catch (Exception e) {
            logger.error("获取匹配结果失败: {}", e.getMessage());
            model.addAttribute("error", "匹配结果不存在或无权访问");
            return "redirect:/job-matching";
        }
    }
    
    /**
     * 显示岗位管理页面
     */
    @GetMapping("/manage")
    public String showJobManagement(Model model, Authentication authentication) {
        User currentUser = (User) authentication.getPrincipal();
        
        // 获取用户创建的岗位
        List<JobDescription> userJobs = jobMatchingService.getAllActiveJobs().stream()
            .filter(job -> job.getCreatedBy().getId().equals(currentUser.getId()))
            .toList();
        
        model.addAttribute("userJobs", userJobs);
        addFormOptions(model);
        
        return "job-management";
    }
    
    /**
     * 显示创建岗位页面
     */
    @GetMapping("/create")
    public String showCreateJobPage(Model model) {
        model.addAttribute("job", new JobDescription());
        addFormOptions(model);
        return "create-job";
    }
    
    /**
     * 处理创建岗位
     */
    @PostMapping("/create")
    public String createJob(@ModelAttribute JobDescription job,
                          Authentication authentication,
                          RedirectAttributes redirectAttributes) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        try {
            // 验证必填字段
            if (job.getTitle() == null || job.getTitle().trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "岗位标题不能为空");
                return "redirect:/job-matching/create";
            }
            
            if (job.getDescription() == null || job.getDescription().trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "岗位描述不能为空");
                return "redirect:/job-matching/create";
            }
            
            if (job.getRequirements() == null || job.getRequirements().trim().isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "岗位要求不能为空");
                return "redirect:/job-matching/create";
            }
            
            // 处理技能列表
            if (job.getRequiredSkills() != null) {
                job.setRequiredSkills(job.getRequiredSkills().stream()
                    .filter(skill -> skill != null && !skill.trim().isEmpty())
                    .map(String::trim)
                    .toList());
            }
            
            JobDescription createdJob = jobMatchingService.createJobDescription(job, currentUser);
            
            redirectAttributes.addFlashAttribute("success", "岗位创建成功！");
            return "redirect:/job-matching/job/" + createdJob.getId();
            
        } catch (Exception e) {
            logger.error("创建岗位失败: {}", e.getMessage());
            redirectAttributes.addFlashAttribute("error", "创建岗位失败：" + e.getMessage());
            return "redirect:/job-matching/create";
        }
    }
    
    /**
     * 显示编辑岗位页面
     */
    @GetMapping("/edit/{jobId}")
    public String showEditJobPage(@PathVariable Long jobId, Model model, Authentication authentication) {
        try {
            JobDescription job = jobMatchingService.getJobById(jobId);
            User currentUser = (User) authentication.getPrincipal();
            
            // 检查权限
            if (!job.getCreatedBy().getId().equals(currentUser.getId())) {
                model.addAttribute("error", "您没有权限编辑此岗位");
                return "redirect:/job-matching/manage";
            }
            
            model.addAttribute("job", job);
            addFormOptions(model);
            
            return "edit-job";
            
        } catch (Exception e) {
            logger.error("获取岗位编辑页面失败: {}", e.getMessage());
            model.addAttribute("error", "岗位不存在或已被删除");
            return "redirect:/job-matching/manage";
        }
    }
    
    /**
     * 处理更新岗位
     */
    @PostMapping("/edit/{jobId}")
    public String updateJob(@PathVariable Long jobId,
                          @ModelAttribute JobDescription job,
                          Authentication authentication,
                          RedirectAttributes redirectAttributes) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        try {
            JobDescription updatedJob = jobMatchingService.updateJobDescription(jobId, job, currentUser);
            
            redirectAttributes.addFlashAttribute("success", "岗位更新成功！");
            return "redirect:/job-matching/job/" + updatedJob.getId();
            
        } catch (Exception e) {
            logger.error("更新岗位失败: {}", e.getMessage());
            redirectAttributes.addFlashAttribute("error", "更新岗位失败：" + e.getMessage());
            return "redirect:/job-matching/edit/" + jobId;
        }
    }
    
    /**
     * 删除岗位
     */
    @PostMapping("/delete/{jobId}")
    public String deleteJob(@PathVariable Long jobId,
                          Authentication authentication,
                          RedirectAttributes redirectAttributes) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        try {
            jobMatchingService.deleteJobDescription(jobId, currentUser);
            
            redirectAttributes.addFlashAttribute("success", "岗位删除成功！");
            return "redirect:/job-matching/manage";
            
        } catch (Exception e) {
            logger.error("删除岗位失败: {}", e.getMessage());
            redirectAttributes.addFlashAttribute("error", "删除岗位失败：" + e.getMessage());
            return "redirect:/job-matching/manage";
        }
    }
    
    /**
     * 搜索岗位
     */
    @GetMapping("/search")
    public String searchJobs(@RequestParam(required = false) String title,
                           @RequestParam(required = false) String company,
                           @RequestParam(required = false) String location,
                           @RequestParam(required = false) String industry,
                           @RequestParam(required = false) String experienceLevel,
                           @RequestParam(required = false) String educationLevel,
                           @RequestParam(required = false) String jobType,
                           Model model,
                           Authentication authentication) {
        
        User currentUser = (User) authentication.getPrincipal();
        
        // 执行搜索
        List<JobDescription> searchResults = jobMatchingService.searchJobs(
            title, company, location, industry, experienceLevel, educationLevel, jobType);
        
        model.addAttribute("jobs", searchResults);
        model.addAttribute("searchPerformed", true);
        
        // 保持搜索条件
        model.addAttribute("searchTitle", title);
        model.addAttribute("searchCompany", company);
        model.addAttribute("searchLocation", location);
        model.addAttribute("searchIndustry", industry);
        model.addAttribute("searchExperienceLevel", experienceLevel);
        model.addAttribute("searchEducationLevel", educationLevel);
        model.addAttribute("searchJobType", jobType);
        
        // 获取用户统计信息
        JobMatchingService.UserMatchStats stats = jobMatchingService.getUserStats(currentUser);
        model.addAttribute("stats", stats);
        
        // 获取用户匹配历史
        List<ResumeMatchResult> matchHistory = jobMatchingService.getUserMatchHistory(currentUser);
        model.addAttribute("matchHistory", matchHistory);
        
        addFormOptions(model);
        
        return "job-matching";
    }
    
    /**
     * 添加表单选项数据
     */
    private void addFormOptions(Model model) {
        // 经验等级选项
        List<String> experienceLevels = Arrays.asList(
            "应届毕业生", "1-3年", "3-5年", "5-10年", "10年以上"
        );
        model.addAttribute("experienceLevels", experienceLevels);
        
        // 学历要求选项
        List<String> educationLevels = Arrays.asList(
            "高中及以下", "大专", "本科", "硕士", "博士"
        );
        model.addAttribute("educationLevels", educationLevels);
        
        // 工作类型选项
        List<String> jobTypes = Arrays.asList(
            "全职", "兼职", "实习", "合同工", "远程工作"
        );
        model.addAttribute("jobTypes", jobTypes);
        
        // 公司规模选项
        List<String> companySizes = Arrays.asList(
            "初创公司(1-20人)", "小型公司(21-100人)", "中型公司(101-500人)", 
            "大型公司(501-1000人)", "超大型公司(1000人以上)"
        );
        model.addAttribute("companySizes", companySizes);
        
        // 行业选项
        List<String> industries = Arrays.asList(
            "互联网/IT", "金融", "教育", "医疗健康", "制造业", 
            "房地产", "零售/电商", "咨询", "媒体/广告", "其他"
        );
        model.addAttribute("industries", industries);
    }
    
    /**
     * 获取匹配等级对应的颜色
     */
    private String getMatchLevelColor(ResumeMatchResult.MatchLevel level) {
        if (level == null) return "secondary";
        
        return switch (level) {
            case EXCELLENT -> "success";
            case GOOD -> "primary";
            case FAIR -> "warning";
            case POOR -> "danger";
            case VERY_POOR -> "dark";
        };
    }
}